//
//  ChangePassWorldVC.m
//  KEREN
//
//  Created by MW on 2023/3/30.
//

#import "ChangePassWorldVC.h"

@interface ChangePassWorldVC (){
    NSInteger _second;
}
@property (nonatomic, strong) UITextField *photoField;
@property (nonatomic, strong) UITextField *codeField;
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UITextField *passwordAsginField;


@end

@implementation ChangePassWorldVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if([UserInfoManager sharedInstance].getUserInfo.password_set){
        [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"修改登录密码"];
    }else{
        [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"设置登录密码"];
    }
    [self setViewLayout];

    // Do any additional setup after loading the view.
}

- (void)setViewLayout{
    _photoField = [UITextField setFlieldplaceholder:@"" Font:Font(16) borderColor:[UIColor clearColor]];
    [self.view addSubview:_photoField];
    [_photoField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(76 + STATUSBAR_HEIGHT);
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(72);
    }];
    //TODO 国际化
    _photoField.backgroundColor = Whire_Color;

    _codeField = [UITextField setFlieldplaceholder:@"请输入验证码" Font:Font(16) borderColor:[UIColor clearColor]];

    if(![UserInfoManager sharedInstance].getUserInfo.password_set){
        _photoField.placeholder = @"请输入手机号码";
        _photoField.keyboardType = UIKeyboardTypeNumberPad;
        [self.view addSubview:_codeField];
        [_codeField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_photoField.mas_bottom).offset(16);
            make.left.offset(24);
            make.right.offset(-24);
            make.height.offset(72);
        }];
    }else{
        _photoField.placeholder = @"请输入原密码";
    }
    _codeField.backgroundColor = Whire_Color;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:_photoField];
    _codeBtn = [UIButton setButtonWithTitle:@"获取验证码" titleColor:Color_7ACC00 titleFont:BFont(16) cornerRadius:0 backColor:[UIColor clearColor]];
    [_codeField addSubview:_codeBtn];
    [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.top.bottom.offset(0);
    }];
    [_codeBtn addTarget:self action:@selector(getPhoneCode) forControlEvents:UIControlEventTouchUpInside];
    _passwordField = [UITextField setFlieldplaceholder:@"请输入新密码" Font:Font(16) borderColor:[UIColor clearColor]];
    [self.view addSubview:_passwordField];
    [_passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        if(![UserInfoManager sharedInstance].getUserInfo.password_set){
            make.top.equalTo(_codeField.mas_bottom).offset(16);
        }else{
            make.top.equalTo(_photoField.mas_bottom).offset(16);
        }
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(72);
    }];
    //TODO 国际化
    _passwordField.backgroundColor = Whire_Color;
    _passwordAsginField = [UITextField setFlieldplaceholder:@"请再次输入新密码" Font:Font(16) borderColor:[UIColor clearColor]];
    [self.view addSubview:_passwordAsginField];
    [_passwordAsginField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordField.mas_bottom).offset(16);
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(72);
    }];
    _passwordAsginField.backgroundColor = Whire_Color;

    UIButton *editBtn = [UIButton setButtonWithTitle:@"确认" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:editBtn];
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordAsginField.mas_bottom).offset(40);
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
    }];
    if(![UserInfoManager sharedInstance].getUserInfo.password_set){
        [editBtn addTarget:self
                    action:@selector(setPassword) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [editBtn addTarget:self
                    action:@selector(changePassword) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)setPassword{
    _passwordField.text = [_passwordField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    _photoField.text = [_photoField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    _passwordAsginField.text = [_passwordAsginField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

    if(![[NSStringManager shareInstance] checkPhone:_photoField.text]){
        return;
    }
    if(![_passwordField.text isEqualToString:_passwordAsginField.text]){
        [[KRAlartManager shareInstance] showErrorAlert:@"新密码前后不一致，请重新设置"];
        return;
    }
    if(![[NSStringManager shareInstance] judgePassWordLegal:_passwordAsginField.text]){
        return;
    }
    
    NSDictionary *parameters = @{@"code":@([_codeField.text intValue]),@"password":_passwordAsginField.text};
    [NetworkingTool POST:User_password_set parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [[UserInfoManager sharedInstance] loginOut];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:USERPHONE];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];

}

- (void)changePassword{
    _passwordField.text = [_passwordField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    _photoField.text = [_photoField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    _passwordAsginField.text = [_passwordAsginField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if(_passwordField.text.length < 1 || _passwordAsginField.text.length < 1 || _photoField.text.length < 1){
        [[KRAlartManager shareInstance] showErrorAlert:@"旧密码或新密码不能为空"];
        return;
    }
    
    
    if(![_passwordField.text isEqualToString:_passwordAsginField.text]){
        [[KRAlartManager shareInstance] showErrorAlert:@"新密码前后不一致，请重新设置"];
        return;
    }
    if([_photoField.text isEqualToString:_passwordAsginField.text]){
        [[KRAlartManager shareInstance] showErrorAlert:@"旧密码和新密码一致，请重新设置"];
        return;
    }
    if(![[NSStringManager shareInstance] judgePassWordLegal:_passwordAsginField.text]){
        return;
    }
    NSDictionary *parameters = @{@"password_old":_photoField.text,@"password_new":_passwordAsginField.text};
    [NetworkingTool POST:User_password_Update parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [[UserInfoManager sharedInstance] loginOut];
        }else{
            //[[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(void)textFiledEditChanged:(NSNotification*)notification{
    UITextField *textField = notification.object;
    NSString *str = textField.text;
    if([UserInfoManager sharedInstance].getUserInfo.password_set){
        if(str.length > 16 && textField.markedTextRange == nil){
            str =  [str substringToIndex:16];
            textField.text = str;
        }
    }else{
        if(str.length > 11){
            str =  [str substringToIndex:11];
            textField.text = str;
        }
    }
}
- (void)getPhoneCode{
    WEAKSELF
    if([[NSStringManager shareInstance] checkPhone:_photoField.text]){
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        self.codeBtn.enabled = NO;
        NSDictionary *parameters = @{@"phone":_photoField.text};
        [NetworkingTool POST:Get_sms_code parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
            [[KRAlartManager shareInstance] hidenAlartView];
            if([response[@"code"] intValue] == 0){
                [weakSelf timer];
            }
        } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        }];
    }

}

- (void)getCodeTimeStr{
    _second --;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%lds",_second] forState:UIControlStateNormal];
    if(_second == 0){
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
        [_timer invalidate];
        _timer = nil;
    }
}



- (NSTimer *)timer{
    if(!_timer){
        _second = 60;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getCodeTimeStr) userInfo:nil repeats:YES];
    }
    return _timer;
}


@end
